const express = require('express')
const router = express.Router()
const multer = require('multer')
const path = require('path')

let fileBaseUrl = ''
// 开发环境
if (process.env.ENV === 'dev') {
  fileBaseUrl = process.env.BASE_URL_DEV + '7a/api/'
} else {
  fileBaseUrl = process.env.BASE_URL + '7a/api/'
}

// 设置存储引擎
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/') // 设置文件上传目录
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9)
    cb(
      null,
      file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname)
    ) // 设置文件名
  },
})

// 初始化上传中间件
const upload = multer({ storage: storage })

// 文件上传接口
router.post('/', upload.single('file'), (req, res) => {
  try {
    // 文件信息
    const file = req.file
    if (!file) {
      return res.status(400).json({ message: '没有文件上传', code: 400 })
    }
    res.status(200).json({
      message: '文件上传成功',
      file: { ...file, path: fileBaseUrl + file?.path },
      code: 200,
    })
  } catch (error) {
    res.status(500).json({ message: error.message, code: 500 })
  }
})

module.exports = router
